// pages/goods/detail/index.js
import {
  getGoodsDetail
} from '../../../api/goods'
import {
  toast
} from '@/utils/extendApi'
import {
  detailBehavior
} from './behavior'
import {
  addCart,
  getCartList
} from '@/api/cart'

Page({
  // 页面的初始数据
  behaviors: [detailBehavior],

  data: {
    goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: '', // 祝福语
    buyNow: null, //默认为null,0代表加入购物车，1代表立即购买
    goodsId: "",
    allCount: 0
  },

  // 加入购物车
  handleAddcart() {
    if (this.data.token) {
      this.setData({
        show: true,
        buyNow: 0
      })
    } else {
      setTimeout(() => {
        toast({
          title: '请登录!',
          icon: 'error'
        })
      }, 400)
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },

  // 立即购买
  handeGotoBuy() {
    if (this.data.token) {
      this.setData({
        show: true,
        buyNow: 1
      })
    } else {
      setTimeout(() => {
        toast({
          title: '请登录!',
          icon: 'error'
        })
      }, 400)

      wx.navigateTo({
        url: '/pages/login/login',
      })
    }

  },
  // 点击确定触发的逻辑
  async submitCart() {
    const {
      goodsInfo: {
        id
      },
      count,
      blessing
    } = this.data
    if (!blessing) {
      toast({
        title: '请输入祝福语',
        icon: 'error'
      })
      return
    }
    if (this.data.buyNow === 0) {

      await addCart({
        goodsId: id,
        count,
        blessing
      })

      this.getCartList()
      toast({
        title: "加入购物车成功",
        icon: 'success'
      })

    } else {
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${id}&blessing=${blessing}`,
      })
    }
    this.setData({
      blessing: ''
    })
    this.onClose()
  },
  async getCartList() {
    const res = await getCartList()
    this.setData({
      allCount: res.data.length
    })
  },
  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({
      show: false
    })
  },
  // 转发朋友，群聊功能
  onShareAppMessage() {
    return {
      title: "真爱有你",
      path: '/pages/index/index',
      imageUrl: '../../../../../assets/images/love.jpg'
    }
  },
  onShareTimeline() {

  },

  // 监听是否更改了购买数量
  onChangeGoodsCount({
    detail
  }) {
    console.log(detail);
    if (detail > 200) return this.setData({
      count: 200
    })
    this.setData({
      count: detail
    })


  },
  // 图片预览功能
  viewImage() {
    wx.previewImage({
      urls: this.data.goodsInfo.detailList
    })
  },
  // 获取商品详情
  async getGoodsDetail() {
    const {
      data
    } = await getGoodsDetail(this.data.goodsId)
    this.setData({
      goodsInfo: data
    })

  },
  onLoad({
    goodsId
  }) {
    this.setData({
      goodsId
    })
    this.getGoodsDetail()
    this.getCartList()
  }
})